package org.itzheng.yuezhi.utils.comm;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Looper;
import android.os.ParcelUuid;
import android.text.TextUtils;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

/**
 * 蓝牙连接工具，连接并读取数据
 * Created by admin on 2017/8/13.
 */

public class BlueToothConnUtils {
    private static final String TAG = "BlueToothConnUtils";
    /**
     * 接收信息的频率
     */
//    private long sleepMillis;
    /**
     * 接收消息的回调，目前先支持一个消息，后期如果需要设置成集合
     */
    private OnReceiveListener mOnReceiveListener;

    public static BlueToothConnUtils getInstance() {
        return new BlueToothConnUtils();
    }

    /**
     * 接收蓝牙的信息的回调
     */
    public void setOnReceiveListener(OnReceiveListener onReceiveListener) {
        this.mOnReceiveListener = onReceiveListener;
    }

    /**
     * 获取消息，这个应该是外面主动调用，时间频率由使用者控制
     */
    public void getMessage() {
        OutputStream outputStream = null;
        try {
            outputStream = bluetoothSocket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            if (mOnReceiveListener != null) {
                mOnReceiveListener.onError(e.toString());
            }
        }
        if (outputStream == null) {
            Log.e(TAG, "连接成功 Exception: " + "outputStream == null");
            if (mOnReceiveListener != null) {
                mOnReceiveListener.onError("outputStream == null");
            }
        } else {
            int size = 1024;
            byte[] buffer = new byte[size];  // buffer store for the stream
            int bytes = size; // bytes returned from read()
            StringBuffer sb = new StringBuffer();
            // Keep listening to the InputStream until an exception occurs
            while (bytes == size) {
                try {
                    // Read from the InputStream
                    InputStream inputStream = bluetoothSocket.getInputStream();
                    bytes = inputStream.read(buffer);
                    sb.append(new String(buffer, 0, bytes));
                    Log.d(TAG, "bytes " + bytes);
                } catch (IOException e) {
                    if (mOnReceiveListener != null) {
                        mOnReceiveListener.onError(e.toString());
                    }
                    return;
                }
            }
            if (mOnReceiveListener != null) {
                mOnReceiveListener.onSuccess(sb.toString());
            }
        }
    }

    /**
     * 接收消息的回调
     */
    public interface OnReceiveListener {
        void onSuccess(String s);

        void onError(String s);

    }

    /**
     * 发送指令,一个发送一个回调应该没问题
     */

    public void sendByte(byte[] bytes, OnSendListener listener) {
        OutputStream outputstream = null;
        try {
            outputstream = bluetoothSocket.getOutputStream();
            outputstream.write(bytes);
            outputstream.flush();//清空发送数据*/
            if (listener != null) {
                listener.onSuccess();
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (listener != null) {
                listener.onError(e.toString());
            }
        }

    }

    /**
     * 发送消息的回调
     */
    public interface OnSendListener {
        void onSuccess();

        void onError(String s);

    }

    /**
     * 给定一个UUID，然后连接蓝牙
     *
     * @param device
     * @param uuid
     * @param listener
     */
    public void connectBlueTooth(final BluetoothDevice device, final String uuid, final OnConnectListener listener) {
//        BluetoothSocket bluetoothSocket = null;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    bluetoothSocket = device.createRfcommSocketToServiceRecord(UUID.fromString(uuid.toString()));
                    bluetoothSocket.connect();//连接的操作
                    Log.i(TAG, "连接成功：" + uuid.toString());
                    if (listener != null) {
                        Looper.prepare();
                        listener.onSuccess(bluetoothSocket);
                        Looper.loop();
                        return;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e(TAG, "Exception: " + e.toString());
                    if (listener != null) {
                        Looper.prepare();
                        listener.onError(e.toString());
                        Looper.loop();
                    }
                }
            }
        }).start();
    }

    BluetoothSocket bluetoothSocket = null;

    public void close(OnCloseListener onCloseListener) {
        if (bluetoothSocket == null) {
            if (onCloseListener != null) {
                onCloseListener.onError("bluetoothSocket == null");
            }
            return;
        }
        if (bluetoothSocket.isConnected()) {
            try {
                bluetoothSocket.close();
                if (onCloseListener != null) {
                    onCloseListener.onSuccess();
                }
            } catch (IOException e) {
                e.printStackTrace();
                if (onCloseListener != null) {
                    onCloseListener.onError(e.toString());
                }
            }
        } else {
            if (onCloseListener != null) {
                onCloseListener.onError("bluetoothSocket no connected");
            }
        }
    }

    /**
     * 没有提供uuid，自己去判断蓝牙设备的uuid
     *
     * @param btDevice
     * @param listener
     */
    private void connectBlueTooth(BluetoothDevice btDevice, OnConnectListener listener) {
        Log.d(TAG, "connectBlueTooth");
        ParcelUuid[] uuids = null;
        if (btDevice.fetchUuidsWithSdp()) {
            uuids = btDevice.getUuids();
        }
        if (uuids == null || uuids.length <= 0) {
            listener.onError("uuid is null");
            return;
        }
        //连接应该用递归
        if (uuids != null && uuids.length > 0) {
//            return uuids[0].toString();
            for (ParcelUuid uuid : uuids) {
//                BluetoothSocket bluetoothSocket =
//                        null;
                try {
                    bluetoothSocket = btDevice.createRfcommSocketToServiceRecord(UUID.fromString(uuid.toString())
                    );
                    bluetoothSocket.connect();//连接的操作
                    Log.i(TAG, "连接成功：" + uuid.toString());
                    if (listener != null) {
                        listener.onSuccess(bluetoothSocket);
                        return;
                    }
                    OutputStream outputStream = bluetoothSocket.getOutputStream();
                    if (outputStream == null) {
                        Log.e(TAG, "连接成功 Exception: " + "outputStream == null");
                    } else {
                        byte[] buffer = new byte[1024];  // buffer store for the stream
                        int bytes; // bytes returned from read()

                        // Keep listening to the InputStream until an exception occurs
                        while (true) {
                            try {
                                // Read from the InputStream
                                InputStream inputStream = bluetoothSocket.getInputStream();
                                bytes = inputStream.read(buffer);
                                String s = buffer.toString();
                                if (!TextUtils.isEmpty(s)) {
                                    Looper.prepare();
//                                    tv_receive_text.setText(s);
                                    Looper.loop();
                                }

                            } catch (IOException e) {
                                break;
                            }
                        }

                        break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e(TAG, "Exception: " + e.toString());
                    if (listener != null) {
                        listener.onError(e.toString());
                    }
                }
            }
        }
    }

    public interface OnConnectListener {
        void onSuccess(BluetoothSocket bluetoothSocket);

        void onError(String Exception);
    }

    public interface OnCloseListener {
        void onSuccess();

        void onError(String Exception);
    }
}
